from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
import json

from database.db import get_db
from models.detection_target import DetectionTarget
from schemas.detection_target import (
    DetectionTargetCreate,
    DetectionTargetUpdate,
    DetectionTargetSchema,
    DetectionTargetList
)
from api.deps import get_current_active_user
from models.user import User

router = APIRouter()

@router.get("", response_model=DetectionTargetList)
def get_detection_targets(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页大小"),
    name: Optional[str] = Query(None, description="目标名称搜索"),
    target_type: Optional[str] = Query(None, description="目标类型筛选"),
    is_active: Optional[bool] = Query(None, description="是否激活筛选"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取检测目标列表"""
    query = db.query(DetectionTarget)
    
    # 应用筛选条件
    if name:
        query = query.filter(DetectionTarget.name.contains(name))
    if target_type:
        query = query.filter(DetectionTarget.target_type == target_type)
    if is_active is not None:
        query = query.filter(DetectionTarget.is_active == is_active)
    
    # 计算总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * page_size
    items = query.offset(offset).limit(page_size).all()
    
    # 转换为响应模型
    item_schemas = []
    for item in items:
        item_dict = {
            "id": item.id,
            "name": item.name,
            "description": item.description,
            "target_type": item.target_type,
            "properties": json.loads(item.properties) if item.properties else None,
            "is_active": item.is_active,
            "created_at": item.created_at,
            "updated_at": item.updated_at
        }
        item_schemas.append(DetectionTargetSchema(**item_dict))
    
    return DetectionTargetList(
        items=item_schemas,
        total=total,
        page=page,
        page_size=page_size
    )


@router.get("/{target_id}", response_model=DetectionTargetSchema)
def get_detection_target(
    target_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取单个检测目标详情"""
    target = db.query(DetectionTarget).filter(DetectionTarget.id == target_id).first()
    if not target:
        raise HTTPException(status_code=404, detail="检测目标不存在")
    
    target_dict = {
        "id": target.id,
        "name": target.name,
        "description": target.description,
        "target_type": target.target_type,
        "properties": json.loads(target.properties) if target.properties else None,
        "is_active": target.is_active,
        "created_at": target.created_at,
        "updated_at": target.updated_at
    }
    
    return DetectionTargetSchema(**target_dict)


@router.post("", response_model=DetectionTargetSchema)
def create_detection_target(
    target: DetectionTargetCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建检测目标"""
    # 创建新检测目标
    db_target = DetectionTarget(
        name=target.name,
        description=target.description,
        target_type=target.target_type,
        properties=json.dumps(target.properties) if target.properties else None,
        is_active=target.is_active
    )
    
    db.add(db_target)
    db.commit()
    db.refresh(db_target)
    
    target_dict = {
        "id": db_target.id,
        "name": db_target.name,
        "description": db_target.description,
        "target_type": db_target.target_type,
        "properties": target.properties,
        "is_active": db_target.is_active,
        "created_at": db_target.created_at,
        "updated_at": db_target.updated_at
    }
    
    return DetectionTargetSchema(**target_dict)


@router.put("/{target_id}", response_model=DetectionTargetSchema)
def update_detection_target(
    target_id: int,
    target_update: DetectionTargetUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新检测目标"""
    db_target = db.query(DetectionTarget).filter(DetectionTarget.id == target_id).first()
    if not db_target:
        raise HTTPException(status_code=404, detail="检测目标不存在")
    
    # 更新字段
    update_data = target_update.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        if field == "properties" and value is not None:
            setattr(db_target, field, json.dumps(value))
        else:
            setattr(db_target, field, value)
    
    db.commit()
    db.refresh(db_target)
    
    target_dict = {
        "id": db_target.id,
        "name": db_target.name,
        "description": db_target.description,
        "target_type": db_target.target_type,
        "properties": json.loads(db_target.properties) if db_target.properties else None,
        "is_active": db_target.is_active,
        "created_at": db_target.created_at,
        "updated_at": db_target.updated_at
    }
    
    return DetectionTargetSchema(**target_dict)


@router.delete("/{target_id}")
def delete_detection_target(
    target_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除检测目标"""
    db_target = db.query(DetectionTarget).filter(DetectionTarget.id == target_id).first()
    if not db_target:
        raise HTTPException(status_code=404, detail="检测目标不存在")
    
    # 检查是否有任务场景使用此检测目标
    if db_target.task_scenarios:
        raise HTTPException(status_code=400, detail="该检测目标正在被任务场景使用，无法删除")
    
    db.delete(db_target)
    db.commit()
    
    return {"message": "检测目标删除成功"}